package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.BaseContext;
import com.itheima.constant.LoginConstant;
import com.itheima.dto.PageUserDTO;
import com.itheima.dto.UserDTO;
import com.itheima.dto.UserLoginDTO;
import com.itheima.entity.SysDict;
import com.itheima.entity.SysMenu;
import com.itheima.entity.SysUser;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.IndexMapper;
import com.itheima.mapper.SysDictMapper;
import com.itheima.mapper.SysMenuMapper;
import com.itheima.mapper.SysUserMapper;
import com.itheima.service.SysUserService;
import com.itheima.utils.IpUtils;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    private final SysUserMapper sysUserMapper;

    private final SysMenuMapper sysMenuMapper;

    private final SysDictMapper sysDictMapper;

    private final IndexMapper indexMapper;
    @Autowired
    private final IpUtils ipUtils;
    @Autowired
    private final JwtUtil jwtUtil;
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1.从数据库中查找用户名是否存在
        SysUser sysUser = sysUserMapper.selectByUserName(userLoginDTO.getLogin_name());
        if(Objects.isNull(sysUser)){
            throw new BusinessException("账号不存在");
        }
        //2.验证密码是否正确
        if(!Objects.equals(sysUser.getPassword(),userLoginDTO.getPassword())){
            throw new BusinessException("密码错误");
        }
        //3.修改最后操作时间,最后登录ip,最后登录时间
        sysUser.setLoginIp(ipUtils.getClientIp());
        sysUser.setLoginDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());
        sysUserMapper.updateById(sysUser);

        //4.生成jwt令牌
        HashMap<String, Object> map = new HashMap<>();
        map.put(LoginConstant.USER_ID,sysUser.getId());
        String jwt = jwtUtil.createJWT(map);

        return UserLoginVO.builder().token(jwt).build();
    }

    /**
     * 获取用户信息
     * @return
     */
    @Override
    public ProfileVO profile() {
        ProfileVO profileVO = new ProfileVO();
        //获取用户信息
        UserInfoVO userInfoVO = getUserInfoVO();
        profileVO.setUserInfo(userInfoVO);

        //获取用户菜单权限
        List<MenuVO> menuVOList = getMenuVOList(userInfoVO);
        profileVO.setMenuList(menuVOList);

        //获取字典表
        Map<String,Object> dictList = getDictList();
        profileVO.setDictList(dictList);

        List<String> btnList = getBtnList();
        profileVO.setBtnList(btnList);


        return profileVO;
    }

    /**
     * 主页统计信息
     * @return
     */
    @Override
    public BaseInfoVO baseInfo() {
        BaseInfoVO baseInfoVO = new BaseInfoVO();
        //所有分类
        List<CateVO> cateVOList = indexMapper.selectAllCate();
        baseInfoVO.setAll_cate(cateVOList);

        //广告位总数
        Integer advposNum = indexMapper.selectNumber();
        baseInfoVO.setAdvpos_num(advposNum);

        //标签总数
        Integer tagNumber = indexMapper.selectTagNumber();
        baseInfoVO.setTag_num(tagNumber);

        //管理员总数
        Integer adminNumber = indexMapper.selectAdminNumber();
        baseInfoVO.setAdmin_num(adminNumber);

        //文章总数
        Integer articleNumber = indexMapper.selectArticleNumber();
        baseInfoVO.setArticle_num(articleNumber);
        //分类总数
        Integer cateNumber = indexMapper.selectCateNumber();
        baseInfoVO.setCate_num(cateNumber);

        //广告图总数
        Integer advImgNumber = indexMapper.selectImgNumber();
        baseInfoVO.setAdvimg_num(advImgNumber);
        //最新用户数据
        List<YddUserVO> yddUserVOList = indexMapper.selectUser();
        baseInfoVO.setNew_user(yddUserVOList);

        //热门文章数据
        List<YddArticleVO> yddArticleVOList = indexMapper.selectHotArticleData();
        baseInfoVO.setHot_article(yddArticleVOList);

        //用户数据
        List<Long> userNumber = indexMapper.selectUserNumber();
        UserNumberVO userNumberVO = new UserNumberVO();
        userNumberVO.setTotal(userNumber.get(0)+userNumber.get(1));
        userNumberVO.setUser_man(userNumber.get(1));
        userNumberVO.setUser_woman(userNumber.get(0));
        baseInfoVO.setUser(userNumberVO);

        return baseInfoVO;
    }

    /**
     * 获取系统配置
     * @return
     */
    @Override
    public ConfigVO getConfig() {
        ConfigVO configVO = new ConfigVO();
        List<Map<String,String>> map = new ArrayList<>();
        map = indexMapper.selectLoginConfig();
        log.info("-----------------");
        /*for (Map<String, String> ssm : map) {
            String login_title = ssm.get("login_title");
            configVO.setLogin_title(login_title);
        }*/
        configVO.setLogin_title(map.get(0).get("attr_value"));
        configVO.setLogin_bg(map.get(1).get("attr_value"));
        configVO.setSystem_name(map.get(2).get("attr_value"));
        configVO.setSystem_logo(map.get(3).get("attr_value"));
        configVO.setWeb_ico(map.get(4).get("attr_value"));

        //ConfigVO configVO = indexMapper.selectLoginConfig();

        return configVO;
    }

    /**
     * 管理员分页查询
     * @param pageUserDTO
     */
    @Override
    public PageInfoVO<UserInfoVO> list(PageUserDTO pageUserDTO) {
        PageInfoVO<UserInfoVO> pageInfoVO = new PageInfoVO<>();
        PageHelper.startPage(pageUserDTO.getPage(),pageUserDTO.getLimit());
        List<SysUser> sysUserList = sysUserMapper.selectByLoginInfo(pageUserDTO.getLogin_name(),pageUserDTO.getStatus(),pageUserDTO.getPhone());
        PageInfo<SysUser> pageInfo = PageInfo.of(sysUserList);
        List<SysUser> sysUserList1 = pageInfo.getList();
        List<UserInfoVO> userInfoVOList = sysUserList1.stream().map(new Function<SysUser, UserInfoVO>() {
            @Override
            public UserInfoVO apply(SysUser sysUser) {
                UserInfoVO userInfoVO = sysUser.transformUserInfoVO();
                List<String> roleIds = userInfoVO.getRole_id();
                List<String> roleNames = sysUserMapper.selectNameByRoleIds(roleIds);
                userInfoVO.setRolename(roleNames);
                return userInfoVO;
            }
        }).collect(Collectors.toList());
        pageInfoVO.setCount(pageInfo.getTotal());
        pageInfoVO.setCurrentPage(pageInfo.getPageNum());
        pageInfoVO.setPageSize(pageUserDTO.getLimit());
        pageInfoVO.setTotalPages(pageInfo.getPages());;
        pageInfoVO.setData(userInfoVOList);
        return pageInfoVO;
    }

    /**
     * 管理员添加
     * @param userDTO
     */
    @Override
    public void save(UserDTO userDTO) {
        SysUser sysUser = userDTO.transformSysUser();
        String userId = UUID.randomUUID().toString();
        sysUser.setId(userId);
        sysUser.setDefaultData("1");
        sysUserMapper.insert(sysUser);
    }

    /**
     * 查询回显
     * @param id
     * @return
     */
    @Override
    public UserInfoVO rowInfo(String id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        UserInfoVO userInfoVO = sysUser.transformUserInfoVO();
        return userInfoVO;
    }

    /**
     * 管理员修改
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
        SysUser sysUser = userDTO.transformSysUser();
        sysUser.setDefaultData("1");
        sysUserMapper.update(sysUser);
    }

    /**
     * 管理员删除
     * @param id
     */
    @Override
    public void deleteById(String id) {
        sysUserMapper.delete(id);
    }


    private List<String> getBtnList() {
        List<String> btnList = new ArrayList<>();
        btnList.add("*");
        return btnList;
    }

    /**
     * 获取字典表
     * @return
     */
    private Map<String, Object> getDictList() {
        HashMap<String,Object> result = new HashMap<>();
        List<SysDict> sysDictList = sysDictMapper.selectDict();
        sysDictList.forEach(sysDict -> {
            HashMap<String, Object> item = new HashMap<>();
            item.put(sysDict.getValue(),sysDict.getLabel());
            result.put(sysDict.getType(),item);
        });
        return result;
    }


    /**
     * 获取菜单列表
     * @param userInfoVO
     */
    private List<MenuVO> getMenuVOList(UserInfoVO userInfoVO) {
        List<String> roleIds = userInfoVO.getRole_id();
        List<SysMenu> sysMenuList = sysUserMapper.selectByRoleIds(roleIds);
        //MenuVo是和前端响应数据挂钩的
        return sysMenuList.stream().map(sysMenu -> {
            MenuVO menuVO = new MenuVO();
            menuVO.setId(sysMenu.getId());
            menuVO.setPid(sysMenu.getPid());
            menuVO.setPath(sysMenu.getPath());
            menuVO.setComponent(sysMenu.getComponent());
            menuVO.setTitle(sysMenu.getTitle());
            menuVO.setIcon(sysMenu.getIcon());
            menuVO.setIs_show(sysMenu.getIsShow());
            menuVO.setIs_cache(sysMenu.getIsCache());
            menuVO.setIs_link(sysMenu.getIsLink());
            menuVO.setRedirect(sysMenu.getRedirect());
            menuVO.setCreateDate(sysMenu.getCreateDate());
            menuVO.setUpdateDate(sysMenu.getUpdateDate());
            menuVO.setDel_flag(sysMenu.getDelFlag());
            menuVO.setType(sysMenu.getType());
            menuVO.setSort(sysMenu.getSort());
            menuVO.setMark(sysMenu.getMark());
            return menuVO;
        }).collect(Collectors.toList());
    }

    /**
     * 获取用户信息
     * @return
     */
    private UserInfoVO getUserInfoVO() {
        UserInfoVO userInfoVO = new UserInfoVO();
        //通过拦截器获得userId
        String loginUserId = BaseContext.getLoginUserId();
        //通过用户id查询所有信息
        SysUser sysUser = sysUserMapper.selectById(loginUserId);
        //拿到角色id --- 记住 数据库是个text(JSON数组)
        String roleIdJsonArr = sysUser.getRoleId();
        if(!Objects.isNull(roleIdJsonArr)){
            //JSON字符串转集合
            //前端要的是字符串集合
            JSONArray jsonArray = JSON.parseArray(roleIdJsonArr);
            List<String> roleIds = jsonArray.toJavaList(String.class);
            userInfoVO.setRole_id(roleIds);
            //通过roleids查rolename
            List<String> roleNames = sysUserMapper.selectByRoleId(roleIds);
            userInfoVO.setRolename(roleNames);
        }
        userInfoVO.setId(sysUser.getId());
        userInfoVO.setLogin_name(sysUser.getLoginName());
        userInfoVO.setName(sysUser.getName());
        userInfoVO.setEmail(sysUser.getEmail());
        userInfoVO.setPhone(sysUser.getPhone());
        userInfoVO.setLogin_ip(sysUser.getLoginIp());
        userInfoVO.setLogin_date(sysUser.getLoginDate());
        userInfoVO.setCreate_date(sysUser.getCreateDate());
        userInfoVO.setUpdate_date(sysUser.getCreateDate());
        userInfoVO.setDel_flag(sysUser.getDelFlag());
        userInfoVO.setStatus(sysUser.getStatus());

        return userInfoVO;
    }
}
